#ifndef SERVERMANAGER_H
#define SERVERMANAGER_H

#include <QObject>
#include <QUrl>

#include "common.h"

class Server;
class ServerChecker;
class QAbstractItemModel;
class QStandardItemModel;

class ServerManager : public QObject
{
    Q_OBJECT

public:
    /**
     * @brief Settings of a server. Used as container for editing.
     */
    struct ServerSettings
    {
        bool checkStats;
        float maxLoad1;
        float maxLoad5;
        float maxLoad15;
        int maxPing;
        QUrl url;
    };

    explicit ServerManager( ServerChecker *serverChecker, QObject *parent = NULL );
    ~ServerManager();

    /**
     * @brief Load servers from files.
     */
    void loadServers();

    /**
     * @return The model.
     */
    QAbstractItemModel* model() const;

    /**
     * @brief Save servers to files.
     */
    void saveServers() const;

    /**
     * @return The server list.
     */
    const ServerList *servers() const;
    
signals:
    /**
     * @brief Will be send if one server has a critical value.
     * @param int The id of the server.
     */
    void serverCritical( int );
    
public slots:
    /**
     * @brief Create a new server.
     * @param name The name.
     * @param url The url.
     * @return The server id.
     */
    int createServer( const QString &name, const QUrl &url );

    /**
     * @brief Delete a server.
     * @param id The id
     */
    void deleteServer( int id );

    /**
     * @brief Edit a server.
     * @param id The id.
     * @param settings The new settings.
     */
    void editServer( int id, ServerManager::ServerSettings settings );

    /**
     * @brief Executes a first check of all servers and
     *        starts the repeated checks.
     */
    void start();

private:
    /**
     * @brief Column ids.
     */
    enum Column
    {
        ColName = 0,
        ColPing = 1,
        ColLoad1 = 2,
        ColLoad5 = 3,
        ColLoad15 = 4
    };

    const int URL_MAX_LENGTH;

    QStandardItemModel *mModel;
    ServerChecker *mServerChecker;
    ServerList mServers;

    /**
     * @brief Set value of column in model.
     * @param row The row.
     * @param column The column.
     * @param ok If false value will be marked.
     * @param text The text.
     */
    void setColumn( int row, Column column, bool ok, const QString &text );

    /**
     * @brief Set model headers.
     */
    void setHeaders();

private slots:
    /**
     * @brief Set server in model.
     * @param id Id of the server.
     */
    void setServer( int id );
};

#endif // SERVERMANAGER_H
